import { jwtVerify } from 'jose';
import { jsonResponse } from "@/utils/index.mjs";
import { headers } from 'next/headers'
import {generateToken, secret, AuthError} from '@/service/auth.mjs';
import { httpCode } from '../../../utils/httpCode.mjs'

export async function GET(req) {
    // 获取请求头
    const headersList = headers()
    const token = headersList.get('authorization')
    if (!token) throw new AuthError('Missing user token')
    try {
        const verified = await jwtVerify(
            token,
            secret
        )
        return jsonResponse(httpCode.OK, {
            token
        })
    } catch (err) {
        console.log(err)
        if (err.code === 'ERR_JWT_EXPIRED') {
            // 如果过期时间在2小时内，则刷新token，否者重新登录
            if ((new Date().getTime() - new Date(err.payload.exp * 1000).getTime()) > 2 * 60 * 60 * 1000) {
                return jsonResponse(httpCode.NEED_LOGIN, {})
            }
            return jsonResponse(httpCode.OK, { token: await generateToken({ user_id: err.payload.user_id})})
        }
        if (err.code === 'ERR_JWS_INVALID') {
            return jsonResponse(httpCode.BAD_REQUEST, {
                message: 'token is error.'
            })
        }
    }
}
